<template>
    <div class="category-level1">
      <!-- 查询区域 -->
      <div class="search-bar">
        <el-input v-model="searchName" placeholder="一级分类名称" style="width: 200px; margin-right: 10px;" />
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="primary" style="float: right;" @click="handleAdd">+ 添加一级分类</el-button>
      </div>
  
      <!-- 数据表格 -->
      <el-table :data="tableData" :loading="loading" style="width: 100%; margin-top: 20px;">
        <el-table-column prop="categoryName" label="一级分类名称" />
        <el-table-column label="二级分类" prop="subCategories">
          <template #default="scope">
            <span v-if="scope.row.subCategories && scope.row.subCategories.length">
              {{ scope.row.subCategories.map(item => item.categoryName).join('、') }}
            </span>
            <span v-else>—</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页 -->
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="tableData.length"
        layout="prev, pager, next, jumper"
        style="margin-top: 20px; text-align: right;"
      />
  
      <!-- 编辑/新增弹窗 -->
      <el-dialog v-model="editDialogVisible" :title="editForm.id ? '编辑' : '添加一级分类'" width="500px">
        <el-form :model="editForm" label-width="100px">
          <el-form-item label="一级分类名称">
            <el-input v-model="editForm.categoryName" placeholder="请输入一级分类名称" />
          </el-form-item>
          <el-form-item label="二级分类">
            <div v-for="(item, idx) in editForm.subCategories" :key="item.id || idx" style="display: flex; margin-bottom: 8px;">
              <el-input v-model="item.categoryName" placeholder="请输入二级分类名称" style="flex:1" />
              <el-button type="danger" icon="el-icon-delete" @click="removeSubCategory(idx)" circle style="margin-left: 8px;" />
            </div>
            <el-button type="primary" @click="addSubCategory" size="small">+ 添加二级分类</el-button>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditConfirm">确定</el-button>
        </template>
      </el-dialog>
  
      <!-- 删除弹窗 -->
      <el-dialog v-model="deleteDialogVisible" title="删除" width="400px">
        <div>您确定要删除"{{ deleteRow?.categoryName }}"一级分类吗？</div>
        <template #footer>
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleDeleteConfirm">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue'
  import { useRouter } from 'vue-router'
  import { fetchCategoryLevel1, addCategory, updateCategory, deleteCategory } from '@/api/safetyCategory'
  
  const router = useRouter()
  const searchName = ref('')
  const currentPage = ref(1)
  const pageSize = ref(10)
  const tableData = ref([])
  const loading = ref(false)
  
  // 弹窗相关
  const editDialogVisible = ref(false)
  const deleteDialogVisible = ref(false)
  const editForm = ref({
    id: null,
    categoryName: '',
    subCategories: []
  })
  const deleteRow = ref(null)
  
  const fetchData = async () => {
    loading.value = true
    try {
      const res = await fetchCategoryLevel1({ name: searchName.value })
      tableData.value = Array.isArray(res.data.data) ? res.data.data : (res.data.data?.records || [])
    } finally {
      loading.value = false
    }
  }
  
  function handleSearch() {
    currentPage.value = 1
    fetchData()
  }
  function handleReset() {
    searchName.value = ''
    currentPage.value = 1
    fetchData()
  }
  function handleAdd() {
    editForm.value = {
      id: null,
      categoryName: '',
      subCategories: []
    }
    editDialogVisible.value = true
  }
  function handleEdit(row) {
    editForm.value = {
      id: row.id,
      categoryName: row.categoryName,
      subCategories: row.subCategories ? row.subCategories.map(item => ({ ...item })) : []
    }
    editDialogVisible.value = true
  }
  function addSubCategory() {
    editForm.value.subCategories.push({ categoryName: '' })
  }
  function removeSubCategory(idx) {
    editForm.value.subCategories.splice(idx, 1)
  }
  async function handleEditConfirm() {
    loading.value = true
    try {
      if (editForm.value.id) {
        // 编辑
        await updateCategory(editForm.value)
      } else {
        // 新增
        await addCategory(editForm.value)
      }
      editDialogVisible.value = false
      fetchData()
    } finally {
      loading.value = false
    }
  }
  function handleDelete(row) {
    deleteRow.value = row
    deleteDialogVisible.value = true
  }
  async function handleDeleteConfirm() {
    loading.value = true
    try {
      await deleteCategory(deleteRow.value.id)
      deleteDialogVisible.value = false
      fetchData()
    } finally {
      loading.value = false
    }
  }
  
  onMounted(() => {
    fetchData()
  })
  </script>
  
  <style scoped>
  .category-level1 {
    background: #fff;
    padding: 24px;
    border-radius: 8px;
  }
  .search-bar {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
  }
  </style>